package chapter8.section4;
//程序8-5：一个Set类的应用

import chapter6.section3.Account;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class AccountRoster {
    private final Set<Account> roster = new HashSet<>();

    public static void main(String[] args) {
        AccountRoster roster = new AccountRoster();
        roster.add(new Account("001", "王华", 2000));
        roster.add(new Account("002", "陆天一", 3000));
        roster.add(new Account("003", "廖凯", 2000));
        System.out.println("--列出当前所有的账户,注意输出顺序和添加时的顺序--");
        roster.print();
    }

    public int size() {    //获得花名册中账户的数量
        return roster.size();
    }

    public void add(Account account) {   //向集合中追加元素
        roster.add(account);
    }

    public void print() {   //显示所有账户信息到默认输出
        Iterator<Account> it = roster.iterator(); //获得集合的迭代器
        while (it.hasNext()) {
            Account account = it.next();
            System.out.println(account.getId());
        }
    }

    //寻找集合中是否存在指定id的账户
    public Account find(String id) {
        Account result = null;
        for (Account account : roster) {
            if (account.getId().equals(id)) {//发现目标
                result = account;
                break;
            }
        }
        return result;
    }
}
